package org.vectrics.recruiter.struts.cv;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.vectrics.cv.ExtraCertificate;
import org.vectrics.cv.Level;
import org.vectrics.cv.PersonSkill;
import org.vectrics.cv.Skill;
import org.vectrics.cv.SkillType;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;

/**
 * Action encargado de persistir en la base los skills seleccionados para
 * asociar a la persona
 * 
 * @author maguero
 */
public class SaveSkillsAction extends VectricsStrutsAction {

    @Override
    protected String doExecute(final VectricsActionData actionData) throws JspException {

        Request request = actionData.getRequest();

        // Si presion� cancelar va al forward cancel
        if (actionData.wasButtonPressed("cancel"))
            return "cancel";

        Long personId = null;
        // Tomo el request para obtener el personId
        if (request.getParameter("personId") != null) {
            personId = new Long(request.getParameter("personId"));
        }

        Person person = null;
        // Si personId es nulo devuelvo una excepci�n
        if (personId != null) {
            person = CoreServiceLocator.getPersonService().findPersonById(personId);
        } else {
            log.error("personId is null");
            throw new JspException("personId is null");
        }

        // borro la lista de skill de la persona
        person.getSkills().clear();

        // recupero todos los skills de la base
        Collection<Skill> skills = CoreServiceLocator.getPersonService().findAllSkills();
        Iterator<ExtraCertificate> certificates = person.getCertificates().iterator();

        // skills.addAll(buildSkills(skills, person.getCertificates()));

        // recorro los certificates
        while (certificates.hasNext()) {
            ExtraCertificate ec = certificates.next();
            String cert = request.getParameter("skill_" + -1 * ec.getId());

            if (StringUtils.isEmpty(cert)) {
                certificates.remove();
            }
        }

        // recorro los skills
        for (Object element : skills) {
            Skill skill = (Skill) element;
            // si es skill hoja y tiene padre
            if ((skill.getChildSkills() == null || skill.getChildSkills().isEmpty()) && skill.getParentSkill() != null) {
                // recupero el check en pantalla
                String valor = request.getParameter("skill_" + skill.getId());
                if (valor != null && !valor.trim().equals("")) {
                    // si esta checkeado el skill, lo recuperamos y tambi�n el
                    // level
                    Skill seleccionado = CoreServiceLocator.getPersonService().findSkillById(skill.getId());
                    String levelValue = request.getParameter("level_" + skill.getId());
                    Level level = null;
                    if (levelValue != null && !levelValue.trim().equals("")) {
                        level = CoreServiceLocator.getPersonService().findLanguageLevelById(new Long(levelValue));
                    } else {
                        List<Level> levels = new ArrayList<Level>(CoreServiceLocator.getPersonService().findAllLevels());
                        level = levels.get(0);
                    }
                    PersonSkill personSkill = new PersonSkill();
                    personSkill.setPerson(person);
                    personSkill.setSkill(seleccionado);
                    personSkill.setLevel(level);
                    person.getSkills().add(personSkill);
                }
            }
        }

        // grabamos los cambios
        CoreServiceLocator.getPersonService().updatePerson(person);

        return "success";
    }

    /**
     * @param skills
     * @param certificates
     * @return
     */
    private Collection<? extends Skill> buildSkills(final Collection<Skill> skills,
            final Set<ExtraCertificate> certificates) {
        Skill parent = null;
        List<Skill> toReturn = new ArrayList<Skill>();

        for (Skill s : skills) {
            if (s.getName().equals("Certificaciones de Microsoft")) {
                parent = s;
                break;
            }
        }

        if (parent != null) {
            for (ExtraCertificate ec : certificates) {
                Skill sk = new Skill();
                sk.setId(-1 * ec.getId());
                sk.setName(ec.getName());
                sk.setParentSkill(parent);
                sk.setType(SkillType.EXTRA_CERTIFICATE);
            }
        }

        return toReturn;
    }

}
